package com.uchengwang.ui.cm_ui.me.ui;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.litesuits.orm.db.model.ColumnsValue;
import com.uchengwang.R;
import com.uchengwang.functions.db.manager.FriendDBManager;
import com.uchengwang.functions.db.manager.GroupDBManager;
import com.uchengwang.functions.db.manager.LiteOrmDBUtil;
import com.uchengwang.functions.http.config.BaseConfig;
import com.uchengwang.functions.http.config.ClubConfig;
import com.uchengwang.functions.http.config.UserConfig;
import com.uchengwang.functions.http.entity.MapRequest;
import com.uchengwang.functions.http.listener.HttpCallBack;
import com.uchengwang.functions.http.listener.IHttpManager;
import com.uchengwang.functions.http.listener.OnResultListener;
import com.uchengwang.functions.http.manager.HttpManager;
import com.uchengwang.ui.UChengApplication;
import com.uchengwang.ui.base_ui.ActivityTitleBar;
import com.uchengwang.ui.base_ui.ui.AllBaseActivity;
import com.uchengwang.ui.cm_ui.cycle.bean.RyGroupBean;
import com.uchengwang.ui.cm_ui.login.bean.UserBean;
import com.uchengwang.ui.cm_ui.rychat.manager.RyGroupManager;
import com.uchengwang.ui.utils.LoadingUtils;
import com.uchengwang.ui.utils.SPUtils;
import com.uchengwang.ui.utils.UCommonUtil;

import java.util.List;

import de.greenrobot.event.EventBus;
import io.rong.imkit.RongIM;
import io.rong.imlib.model.Group;
import io.rong.imlib.model.UserInfo;

/**
 * Created by U城网 on 2017/6/12.
 * 编辑信息界面
 */

public class EditorInfoActivity extends AllBaseActivity{
    //编辑不同的信息对应不同的type
    //1编辑个人昵称 2个人标语 3个人家乡 4个人感情状态 5更改个人备注
    //6编辑社团标语 7编辑社团合作联系人 8编辑社团合作联系人的手机号 9编辑社团简介
    //15 修改群名称 15及以上是针对群的 16群描述
    private int type;

    private ActivityTitleBar titleBa;
    private EditText editor;
    private TextView num;
    private int length;
    private IHttpManager.RequestMethod method;
    private String url, editString, typeS = "";
    private MapRequest mapRequest;
    private long groupId;//为群ID
    private String nickName = "";//被设置备注名人的昵称

    private long remarkUid;//设置备注人的ID

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor_info);

        typeS = getIntent().getStringExtra(BaseConfig.TYPE_STRING);
        type = getIntent().getIntExtra(BaseConfig.TYPE, -1);
        groupId = getIntent().getLongExtra(BaseConfig.ID, 0);
        nickName = getIntent().getStringExtra(BaseConfig.NICK_NAME);
        remarkUid = getIntent().getLongExtra(BaseConfig.REMARK_UID, -1);//更改备注时必须
        initView();

    }
    private void initView(){
        titleBa = (ActivityTitleBar) findViewById(R.id.editor_titleBa);
        editor = (EditText) findViewById(R.id.editor_editor);
        editor.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (!TextUtils.isEmpty(charSequence)){
                    if (type ==1 && charSequence.length() >15){
                        num.setText("");
                    }else {
                        num.setText(charSequence.length()+"/"+length);
                    }
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {
            }
        });
        num = (TextView) findViewById(R.id.editor_num);

        initViewData();

    }

    private void initViewData(){

        switch (type){
            case 1:
                titleBa.setTitle("昵称", 0);
                int l = typeS.length();
                if (l <=15){
                    l = 15;
                }
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(l)});
                num.setText("0/15");
                length = 15;
                break;
            case 2:
                titleBa.setTitle("个性签名", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                num.setText("0/50");
                length = 50;
                break;
            case 3://
                titleBa.setTitle("家乡", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(30)});
                num.setText("0/30");
                length = 30;
                break;
            case 4:
                titleBa.setTitle("感情状态", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                num.setText("0/50");
                length = 50;
                break;
            case 5:
                titleBa.setTitle("备注信息", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
                num.setText("0/10");
                length = 10;
                break;
            case 6:
                titleBa.setTitle("社团标语", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(50)});
                num.setText("0/50");
                length = 50;
                break;
            case 7:
                titleBa.setTitle("合作联系人", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});
                num.setText("0/10");
                length = 10;
                break;
            case 8:
                titleBa.setTitle("联系手机号", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});
                num.setText("0/11");
                length = 11;
                editor.setInputType(InputType.TYPE_CLASS_NUMBER);
                break;
            case 9:
                titleBa.setTitle("社团简介", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(300)});
                num.setText("0/300");
                length = 300;
                break;
            case 15:
                titleBa.setTitle("群名称", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(15)});
                num.setText("0/15");
                length = 15;
                break;
            case 16:
                titleBa.setTitle("群描述", 0);
                editor.setFilters(new InputFilter[]{new InputFilter.LengthFilter(300)});
                num.setText("0/300");
                length = 300;
                break;
        }

        if (!TextUtils.isEmpty(typeS)){
            editor.setText(typeS);
            editor.setSelection(typeS.length());
            if (type ==1 && typeS.length() >15){
                num.setText("");
            }else {
                num.setText(typeS.length()+"/"+length);
            }
        }

        titleBa.setRightText("完成", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //完成提交网络
                editString = editor.getText().toString();
                editString = editString.trim();
                //修改备注名 为空时，表示取消备注
                if (TextUtils.isEmpty(editString) && type != 5){
                    UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "请填写信息");
                    return;
                }

                if (!TextUtils.isEmpty(typeS) && typeS.equals(editString)){
                    EditorInfoActivity.this.finish();
                    return;
                }

                LoadingUtils.getUtils().loading(EditorInfoActivity.this);
                mapRequest = new MapRequest();
                if (type <5){
                    //修改个人信息
                    method = UserConfig.ChangeInfo.method_change;
                    url = UserConfig.ChangeInfo.URL;
                    switch (type){
                        case 1://修改个人信息
                            if (editString.length() >15){
                                LoadingUtils.getUtils().hide();
                                UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "昵称不能超过15个字符");
                                return;
                            }

                            mapRequest.put(BaseConfig.NICK_NAME, editString);
                            break;
                        case 2://个人标语
                            mapRequest.put(BaseConfig.USER_SIGN, editString);
                            break;
                        case 3://家乡
                            mapRequest.put(BaseConfig.HOME_TOWN, editString);
                            break;
                        case 4://感情状态
                            mapRequest.put(BaseConfig.EMOTION_STATE, editString);
                            break;
                    }

                }else{
                    method = ClubConfig.Club.method_change;
                    url = ClubConfig.Club.URL;
                    switch (type){
                        case 6://修改社团标语
                            mapRequest.put(BaseConfig.ORG_SIGN, editString);
                            break;
                        case 7://合作联系人
                            mapRequest.put(BaseConfig.CONTACT_PERSON, editString);
                            break;
                        case 8://联系电话
                            mapRequest.put(BaseConfig.CONTACT, editString);
                            break;
                        case 9://社团简介
                            mapRequest.put(BaseConfig.ORG_DESCRIPTION, editString);
                            break;
                        case 15://修改群名称
                            mapRequest.put(BaseConfig.ID, groupId);
                            mapRequest.put(BaseConfig.GROUP_NAME_UCW, editString);
                            group(mapRequest);
                            break;
                        case 16://修改群描述
                            mapRequest.put(BaseConfig.ID, groupId);
                            mapRequest.put(BaseConfig.GROUP_DESC, editString);
                            group(mapRequest);
                            break;
                    }
                }

                if (type <15){
                    if (type ==5){
                        remarkName();
                    }else {
                        postInfo(method, url, mapRequest);
                    }
                }


            }
        });
    }

    /**
     * 将信息提交到
     * */
    private void postInfo(IHttpManager.RequestMethod method, String url, MapRequest map){

        HttpManager.newInstance(this).query(method, url, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "stutas="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "修改失败");
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "stutas="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                if (status != 0){
                    UCommonUtil.getUtil().showToast(EditorInfoActivity.this, msg);
                    return;
                }
                UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "修改成功");
                BaseConfig.isRelease = true;
                switch (type){
                    case 1://修改个人信息 昵称
                        UChengApplication.nickName = editString;
                        SPUtils.getPreferences(EditorInfoActivity.this).putString(BaseConfig.NICK_NAME, editString);
                        break;
                    case 2://个人标语
                        SPUtils.getPreferences(EditorInfoActivity.this).putString(BaseConfig.USER_SIGN, editString);
                        break;
                }
                Intent intent = new Intent();
                intent.putExtra(BaseConfig.CONTENT, editString);
                intent.putExtra(BaseConfig.TYPE, type);
                setResult(1, intent);
                EditorInfoActivity.this.finish();
            }
        });

    }

    /**
     * 修改备注名
     * */
    private void remarkName(){
        MapRequest map = new MapRequest();
        map.put(BaseConfig.REMARK_NAME, editString);
        map.put(BaseConfig.REMARK_UID, remarkUid);

        HttpManager.newInstance(this).query(UserConfig.RemarkName.method, UserConfig.RemarkName.URL, map, new HttpCallBack() {
            @Override
            public void onError(int status, String msg) {
                Log.d("jjf", "stutas="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "修改失败");
            }

            @Override
            public void onResp(int status, String msg, String data) {
                Log.d("jjf", "stutas="+status+"=msg="+msg);
                LoadingUtils.getUtils().hide();
                if (status != 0){
                    UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "修改失败");
                    return;
                }

                if (TextUtils.isEmpty(editString)){
                    editString = nickName;//将昵称更新进去
                }
                ColumnsValue value = new ColumnsValue(new String[]{"remarkName"}, new Object[]{editString});
                FriendDBManager.getManager().updateUserInfo(EditorInfoActivity.this, remarkUid, value);

                List<UserBean> list = LiteOrmDBUtil.getLiteOrm(EditorInfoActivity.this).getQueryByWhere(UserBean.class, "id", String.valueOf(remarkUid));
                if (list != null && list.size() >0){
                    UserBean userBean = list.get(0);

                    String headUrl = "";
                    if (TextUtils.isEmpty(userBean.getUserAvatar())){
                        headUrl = "http://ucw-user.oss-cn-shanghai.aliyuncs.com/default_image.jpg";
                    }else {
                        headUrl = userBean.getUserAvatar();
                    }
                    UserInfo userInfo = new UserInfo(String.valueOf(remarkUid), editString, Uri.parse(headUrl));
                    RongIM.getInstance().refreshUserInfoCache(userInfo);
                }

                UserBean b = new UserBean();
                b.setId(remarkUid);
                b.setRemarkName(editString);
                EventBus.getDefault().post(b);//修改备注名成功

                Intent intent = new Intent();
                intent.putExtra(BaseConfig.CONTENT, editString);
                setResult(1, intent);
                EditorInfoActivity.this.finish();
            }
        });
    }

    /**
     * 修改群相关
     * */
    private void group(MapRequest map){
        RyGroupManager.getManager().changeGroupInfo(this, map, new OnResultListener() {
            @Override
            public void onResult(int stutas, String msg, int total, String data) {
                LoadingUtils.getUtils().hide();
                if (stutas ==0){
                    UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "修改成功");
                    switch (type){
                        case 15://修改群名称
                            ColumnsValue value = new ColumnsValue(new String[]{"groupName"}, new Object[]{editString});
                            GroupDBManager.getManager().updateGroupInfo(EditorInfoActivity.this, groupId, value);

                            List<RyGroupBean> list = LiteOrmDBUtil.getLiteOrm(EditorInfoActivity.this).getQueryByWhere(RyGroupBean.class, "id", String.valueOf(groupId));
                            if (list != null && list.size() >0){
                                RyGroupBean groupBean = list.get(0);
                                Group group = new Group(String.valueOf(groupId), editString, Uri.parse(groupBean.getGroupLogo()));
                                RongIM.getInstance().refreshGroupInfoCache(group);
                            }

                            break;
                        case 16://修改群描述
                            ColumnsValue v = new ColumnsValue(new String[]{"groupDesc"}, new Object[]{editString});
                            GroupDBManager.getManager().updateGroupInfo(EditorInfoActivity.this, groupId, v);
                            break;
                    }

                    Intent intent = new Intent();
                    intent.putExtra(BaseConfig.ORG_NAME, editString);
                    setResult(1, intent);
                    EditorInfoActivity.this.finish();
                }else {
                    UCommonUtil.getUtil().showToast(EditorInfoActivity.this, "修改失败");
                }
            }
        });
    }

}
